package models

import (
	"github.com/spf13/cast"
	"hc_server/routers/response/merchantResponse"
)

// LianCode 联动省市区编码
type LianCode struct {
	ID           uint   `json:"id" form:"id" gorm:"primary_key;AUTO_INCREMENT;comment:'id'"`
	Name         string `json:"name" gorm:"comment:'地区名称'"`
	Level        int    `json:"level" gorm:"comment:'层级（1省2市3区）'"`
	ProvinceCode string `json:"province_code" gorm:"comment:'省'"`
	CityCode     string `json:"city_code" gorm:"comment:'市'"`
	AreaCode     string `json:"area_code" gorm:"comment:'区'"`
}

// LianCodeList 联动获取省市区列表
func LianCodeList() []*merchantResponse.GetLianCodeListList {
	var codes []*LianCode
	var results = make([]*merchantResponse.GetLianCodeListList, 0)

	db.Model(&LianCode{}).Scan(&codes)

	for _, c := range codes {
		if c.Level == 1 {
			results = append(results, &merchantResponse.GetLianCodeListList{
				Id:   cast.ToString(c.ID),
				Code: c.ProvinceCode,
				Name: c.Name})
		}
	}

	for _, result := range results {
		var cities = make([]*merchantResponse.GetLianCodeListList, 0)
		for _, c := range codes {
			if c.Level == 2 && c.ProvinceCode == result.Code {
				cities = append(cities, &merchantResponse.GetLianCodeListList{
					Id:   cast.ToString(c.ID),
					Code: c.CityCode,
					Name: c.Name})
			}
		}

		var areas = make([]*merchantResponse.GetLianCodeListList, 0)
		for _, city := range cities {
			for _, c := range codes {
				if c.Level == 3 && c.CityCode == city.Code {
					areas = append(areas, &merchantResponse.GetLianCodeListList{
						Id:   cast.ToString(c.ID),
						Code: c.AreaCode,
						Name: c.Name})
				}
			}
			city.List = areas
		}
		result.List = cities
	}

	return results
}

// GetLianCode 获取联动省市区编码
func GetLianCode(id interface{}) *LianCode {
	var code *LianCode
	db.Model(&LianCode{}).Where("id = ?", id).Scan(&code)
	return code
}
